package com.axzhengxin.platform.axcube.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.axzhengxin.platform.axcube.service.IAxCubeService;
import com.axzhengxin.platform.axcube.service.IElasticSearchAgentService;
import com.axzhengxin.platform.axcube.transf.ElasticSearchAgentRequest;
import com.axzhengxin.platform.axcube.transf.EntInfoListQueryRequest;
import com.axzhengxin.platform.axcube.transf.desc.*;
import com.axzhengxin.platform.common.service.IDbExecService;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * AxCubeServiceImpl
 *
 * @author jiangnan
 * @date 2021/3/18
 */
@Service
public class AxCubeServiceImpl implements IAxCubeService {

    /**
     * 金额相关的变更事项代码
     */
    private static final String JBXXBG_BGSX_JE = "'913','914','117','118','127','131','134','135','136','155','157','170'";
    private static final String JYYC = "EGOV_RWPH_JYYC";
    private static final String JYYC_LRYCYY = "列入异常名录原因";
    private static final String JYYC_YCYCYY = "移出异常名录原因";
    private static final String JBXX = "EGOV_BASC_JBXX";
    private static final String JBXX_DJJG = "登记机关";
    private static final String GQCZ = "EGOV_BASC_GQCZDJ";
    private static final String GQCZ_CZRLX = "出质人类型";
    private static final String GQCZ_ZQRLX = "质权人类型";
    private static final String STATE = "状态";
    private static final String DCDY = "EGOV_BASC_DCDYDJ";

    private IElasticSearchAgentService elasticSearchAgentService;
    private IDbExecService dbExecService;

    public AxCubeServiceImpl(IElasticSearchAgentService elasticSearchAgentService,
                             IDbExecService dbExecService) {
        this.elasticSearchAgentService = elasticSearchAgentService;
        this.dbExecService = dbExecService;
    }

    @Override
    public TableDataInfo getEntList(EntInfoListQueryRequest request, int pageNum, int pageSize) {
        if (request.isValidRequest()) {
            ElasticSearchAgentRequest agentRequest = new ElasticSearchAgentRequest()
                    .setSearchKey(request.getContent())
                    .setFrom(pageNum)
                    .setSize(pageSize)
                    .setSearchType(request.getSearchType())
                    .setFilters(request.initQueryFilter());
            return Optional.ofNullable(elasticSearchAgentService.getEntInfoList(agentRequest))
                    .map(resp -> {
                        TableDataInfo info = new TableDataInfo();
                        info.setCode(200);
                        info.setRows(resp.getData());
                        info.setTotal(resp.getTotal());
                        return info;
                    })
                    .orElseGet(() -> {
                        TableDataInfo info = new TableDataInfo();
                        info.setCode(200);
                        return info;
                    });

        } else {
            TableDataInfo info = new TableDataInfo();
            info.setCode(200);
            return info;
        }
    }

    /**
     * 查询企业基本信息
     *
     * @param entName 企业名称
     * @return 基本信息数据
     */
    @Override
    public SjqJbxx getEntInfo(String entName) {
        return dbExecService.getJbxxByEntName(entName)
                .map(data -> data.toJavaObject(SjqJbxx.class))
                .map(jbxx -> {
                    if (StrUtil.isNotBlank(jbxx.getOplocdistrict())) {
                        jbxx.setOplocdistrict(dbExecService.getHshyCodeByColValueAndName(jbxx.getOplocdistrict(), "OPLOCDISTRICT"));
                    }
                    if (StrUtil.isNotBlank(jbxx.getIndustryphy())) {
                        jbxx.setIndustryphy(dbExecService.getHshyCodeByColValueAndName(jbxx.getIndustryphy(), "INDUSTYPE"));
                    }
                    if (Objects.nonNull(jbxx.getEstdate())) {
                        jbxx.setEstdatestr(DateUtils.dateTime(jbxx.getEstdate()));
                    }
                    if (Objects.nonNull(jbxx.getOpfrom()) && Objects.nonNull(jbxx.getOpto())) {
                        String optfrom = DateUtils.dateTime(jbxx.getOpfrom());
                        String optostr = DateUtils.dateTime(jbxx.getOpto());
                        jbxx.setOplimit(optfrom + " ~ " + optostr);
                    }
                    if (Objects.nonNull(jbxx.getApprdate())) {
                        jbxx.setApprdatestr(DateUtils.dateTime(jbxx.getApprdate()));
                    }
                    return jbxx;
                })
                .orElse(new SjqJbxx());
    }

    @Override
    public List<SjqGdjczdj> getGdjczdj(String entId) {
        return dbExecService.getGdjczdj(entId)
                .toJavaList(SjqGdjczdj.class)
                .stream()
                .peek(e -> {
                    if (StrUtil.isNotBlank(e.getInvtype())) {
                        String invTypeDesc = dbExecService.getDictValue("EGOV_BASC_GDJCZDJ", "股东类型", e.getInvtype());
                        e.setInvtype(invTypeDesc);
                    }
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<SjqZyry> getZyry(String entId) {
        return dbExecService.getZyry(entId)
                .toJavaList(SjqZyry.class)
                .stream()
                .peek(e -> {
                    if (StrUtil.isNotBlank(e.getPosition())) {
                        String positionDesc = dbExecService.getGsCodeLibraryByBkeyBname("EGOV_BASC_JBXX", e.getPosition());
                        e.setPosition(positionDesc);
                    }
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<EgovJbxxbg> getJbxxbg(String entId) {
        return dbExecService.getJbxxBg(entId)
                .toJavaList(EgovJbxxbg.class)
                .stream()
                // 变更时间处理
                .peek(e -> {
                    if (StrUtil.isNotBlank(e.getAccdate())
                            && e.getAccdate().length() > 10) {
                        e.setAccdate(e.getAccdate().substring(0, 10));
                    }
                })
                // 变更金额相关处理
                .peek(e -> {
                    if (JBXXBG_BGSX_JE.contains(e.getAltitem())) {
                        if (StrUtil.isNotBlank(e.getAltbe())
                                && e.getAltbe().contains(".")) {
                            String altbe = e.getAltbe().substring(0, e.getAltbe().lastIndexOf("."));
                            e.setAltbe(altbe);
                        }
                        if (StrUtil.isNotBlank(e.getAltaf())
                                && e.getAltaf().contains(".")) {
                            String altaf = e.getAltaf().substring(0, e.getAltaf().lastIndexOf("."));
                            e.setAltaf(altaf);
                        }
                    }
                })
                // 变更事项处理
                .peek(e -> {
                    String altItemDesc = Optional.of(
                            dbExecService.getDictValue("EGOV_BASC_JBXXBG", "变更事项", e.getAltitem()))
                            .filter(StrUtil::isNotBlank)
                            .orElse("其他事项备案");
                    e.setAltitem(altItemDesc);
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<EgovJyyc> getJyyc(String entId) {
        return dbExecService.getJyyc(entId)
                .toJavaList(EgovJyyc.class)
                .stream()
                .peek(e -> e.setSpecause(dbExecService.getDictValue(JYYC, JYYC_LRYCYY, e.getSpecause())))
                .peek(e -> e.setRemexcpres(dbExecService.getDictValue(JYYC, JYYC_YCYCYY, e.getRemexcpres())))
                .peek(e -> e.setOrgan(dbExecService.getDictValue(JBXX, JBXX_DJJG, e.getOrgan())))
                .peek(e -> {
                    if (Objects.nonNull(e.getAbntime())) {
                        e.setAbntimestr(DateUtils.dateTime(e.getAbntime()));
                    }
                })
                .peek(e -> {
                    if (Objects.nonNull(e.getRemdate())) {
                        e.setRemdatestr(DateUtils.dateTime(e.getRemdate()));
                    }
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<EgovXzcf> getXzcf(String entId) {
        return dbExecService.getXzcf(entId)
                .toJavaList(EgovXzcf.class)
                .stream()
                .peek(e -> {
                    if (Objects.nonNull(e.getPendecissdate())) {
                        e.setPendecissdatestr(DateUtils.dateTime(e.getPendecissdate()));
                    }
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<EgovXzxk> getXzxk(String entId) {
        return dbExecService.invoke("getXzxkByMarprid", entId)
                .toJavaList(EgovXzxk.class)
                .stream()
                .peek(e -> {
                    if (Objects.nonNull(e.getCreatedate())) {
                        e.setCreatedatestr(DateUtils.dateTime(e.getCreatedate()));
                    }
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<EgovDwtz> getDwtz(String entId, String entName) {
        return dbExecService.invoke("getDwtzByMarprid", entId)
                .toJavaList(EgovDwtz.class)
                .stream()
                .peek(e -> {
                    e.setDwtz(e.getEntname());
                    dbExecService.invoke("getJbxxByUniscid", e.getRegno())
                            .toJavaList(SjqJbxx.class)
                            .stream()
                            .findFirst()
                            .ifPresent(jbxx -> {
                                String id = jbxx.getId();
                                String percent = IDbExecService.getField(dbExecService.invoke("queryPercent", id, entName), "CONPROP");
                                if (NumberUtil.isDouble(percent)) {
                                    e.setCzbl(Double.parseDouble(percent));
                                }
                                e.setTzfrdb(jbxx.getLerep());
                                e.setTzzczb(jbxx.getRegcap().doubleValue());
                                e.setTzestdate(DateUtils.dateTime(jbxx.getEstdate()));
                                e.setTzstate(jbxx.getState());
                            });
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<EgovGqczdj> getGqczdj(String entId) {
        return dbExecService.invoke("getGqczdjByMarprid", entId)
                .toJavaList(EgovGqczdj.class)
                .stream()
                .peek(egovGqczdj -> {
                    if (egovGqczdj.getPlestyle() != null) {
                        String plesty = dbExecService.getDictValue(GQCZ, GQCZ_CZRLX, egovGqczdj.getPlestyle());
                        egovGqczdj.setPlestyle(plesty);
                    }
                    if (egovGqczdj.getImporgtype() != null) {
                        String imporgtype = dbExecService.getDictValue(GQCZ, GQCZ_ZQRLX, egovGqczdj.getImporgtype());
                        egovGqczdj.setPlestyle(imporgtype);
                    }
                    if (egovGqczdj.getState() != null) {
                        String state = dbExecService.getDictValue(GQCZ, STATE, egovGqczdj.getState());
                        egovGqczdj.setState(state);
                    }
                    if (egovGqczdj.getAccdate() != null) {
                        egovGqczdj.setAccdatestr(DateUtils.dateTime(egovGqczdj.getAccdate()));
                    }
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<EgovDcdydj> getDcdydj(String entId) {
        return dbExecService.invoke("queryDcdydjByMarprid", entId)
                .toJavaList(EgovDcdydj.class)
                .stream()
                .peek(egovDcdydj -> {
                    if (egovDcdydj.getOrgid() != null) {
                        String orgid = dbExecService.getDictValue(JBXX, JBXX_DJJG, egovDcdydj.getOrgid());
                        egovDcdydj.setOrgid(orgid);
                    }
                    if (egovDcdydj.getState() != null) {
                        String state = dbExecService.getDictValue(DCDY, STATE, egovDcdydj.getState());
                        egovDcdydj.setState(state);
                    }
                    if (egovDcdydj.getRegdate() != null) {
                        egovDcdydj.setRegdatestr(DateUtils.dateTime(egovDcdydj.getRegdate()));
                    }
                })
                .collect(Collectors.toList());
    }

}
